package app

import (
	"crypto/md5"
	"crypto/sha1"
	// "crypto/sha256"
	// "encoding/asn1"
	"encoding/base64"
	// "encoding/hex"
	"io"
	"os"
	"path/filepath"

	// "time"

	"github.com/go-apibox/api"
)

func GetAttPath(attId string) string {
	return filepath.Join(app.config.DataDir, attId)

}

func SealPW(pw string) string {
	h := sha1.New()
	sum := h.Sum([]byte(pw + SALT))
	return base64.StdEncoding.EncodeToString(sum)
}

func VerifyPW(pw, spw string) bool {
	return SealPW(pw) == spw
}

func md5SumStr(str string) string {
	h := md5.New()
	h.Write([]byte(str))
	buf := h.Sum(nil)
	return base64.StdEncoding.EncodeToString(buf)
}

func md5SumFile(path string) (string, error) {
	h := md5.New()
	fd, err := os.OpenFile(path, os.O_RDONLY, 0644)
	if err != nil {
		return "", err
	}
	defer fd.Close()
	io.Copy(h, fd)
	buf := h.Sum(nil)
	return base64.StdEncoding.EncodeToString(buf), nil

}

func isAdmin(c *api.Context) (isAdmin bool, uid uint64, err error) {
	session, err := c.Session("default")
	if err == nil {
		isAdmin = session.Values["UserType"].(string) == USER_TYPE_ADMIN
		uid = session.Values["UserId"].(uint64)
	}

	return isAdmin, uid, err

}
